<template>
  <div>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-row :gutter="24">
        <el-col :span="12" :offset="0">
          <el-form-item label="出库类型">
            <el-input v-model="ruleForm.outType" />
            <!-- <p>接收到的值为：{{ ruleForm.outType }}</p> -->
          </el-form-item>
          <el-form-item label="出库单号" prop="outNum">
            <el-input v-model="ruleForm.outNum" />
            <el-checkbox v-model="systemNumberChecked" @change="generateSystemNumber" name="type">系统编号</el-checkbox>
          </el-form-item>
          <el-form-item label="出库主题" prop="outTopic">
            <el-input v-model="ruleForm.outTopic" />
          </el-form-item>
          <el-form-item label="出库日期">
            <el-form-item prop="outDate">
              <el-date-picker v-model="ruleForm.outDate" type="date" placeholder="Pick a Date" format="YYYY/MM/DD"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="出库仓库" prop="Warehouse">
            <el-cascader v-model="Warehouse" :options="warehousesOptions"
              :props="{ value: 'label', label: 'label', children: 'children' }" @change="getOutList" clearable
              filterable placeholder="请选择仓库" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="生产单号" prop="ProCode">
            <el-input v-model="ruleForm.ProCode" @click="dialogTableVisible = true" />
          </el-form-item>
          <el-form-item label="领料人员" prop="applicant">
            <el-input v-model="ruleForm.applicant" />
          </el-form-item>
          <el-form-item label="出库人员" prop="outName">
            <el-input v-model="ruleForm.outName" />
          </el-form-item>
          <el-form-item label="出库数量" prop="outCount">
            <el-input v-model="ruleForm.outCount" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 生产单号弹出框开始 -->
    <el-dialog v-model="dialogTableVisible" title="选择生产单号" width="800">
      <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="70" align="left">
          <template #default="scope">
            {{ scope.$index + (pagination.pageIndex - 1) * pagination. pageSize + 1 }}
          </template>
        </el-table-column>
        <el-table-column property="ProCode" label="生产单号" width="120" />
        <el-table-column property="ProDate" label="单据日期" width="120">
          <template #default="scope">
            {{ scope.row.ProDate.substr(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column property="ProPeo" label="负责人" width="120" />
        <el-table-column property="ProPhone" label="联系电话" width="120" />
        <el-table-column property="ProPeople" label="生产人员" width="120" />
        <el-table-column property="ProStatus" label="生产状态" width="120">
          <template #default="scope">
            <span v-if="scope.row.ProStatus === 0">未完成</span>
            <span v-if="scope.row.ProStatus === 1">已完成</span>
            <span v-if="scope.row.ProStatus === 2">未入库</span>
            <span v-if="scope.row.ProStatus === 3">已入库</span>
            <span v-if="scope.row.ProStatus === 4">已出库</span>
          </template>
        </el-table-column>
        <el-table-column property="ProDesc" label="备注" width="120" />
        <el-table-column property="ProDateInfo" label="生产日期" width="120">
          <template #default="scope">
            {{ scope.row.ProDateInfo.substr(0, 10) }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pagination.pageSize"
        :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="addProduceCode">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 生产单号弹出框结束 -->
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import type { ElTable, FormInstance, FormRules } from "element-plus";
import axios from "axios";
import { ElCascader, ElMessage } from "element-plus";
//引用路由
import { useRouter, useRoute } from "vue-router";
import { formatDate } from "../outtabs(库存管理)/filter.js"
//定义弹出框默认值
const dialogTableVisible = ref(false)
const multipleTableRef = ref([]);
const tableData = ref<Product[]>([])
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
//生产表（关联出库用）
interface Product {
  ProId: number
  ProCode: string
  ProDate: string
  ProPeo: string
  ProPhone: string
  ProPeople: string
  ProDesc: string
  ProDateInfo: string,
  ProStatus: number,
}
const router = useRouter();
interface RuleForm {
  outType: string;
  outNum: string;
  outTopic: string;
  outDate: string;
  outWareHouse: string;
  applicant: string;
  outName: string;
  remark: string;
  outCount: number;
  ProCode: string//生产单号
}
const route = useRoute();
const Warehouse = ref([]);
const warehousesOptions = ref([]);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  outType: "",
  outNum: "",
  outTopic: "",
  outDate: "",
  outWareHouse: "",
  applicant: "",
  outName: "",
  remark: "",
  outCount: "",
  ProCode: ""//生产单号
});

const rules = reactive<FormRules<RuleForm>>({
  outType: [
    { required: true, message: '请输入出库类型', trigger: 'blur' },
  ],
  outNum: [
    { required: true, message: '请输入出库单号', trigger: 'blur' },
  ],
  outTopic: [
    { required: true, message: '请输入出库主题', trigger: 'blur' },
  ],
  outDate: [
    { required: true, message: '请输入出库日期', trigger: 'blur' },
  ],
  outWareHouse: [
    { required: true, message: '请输入出库仓库', trigger: 'change' },
  ],
  applicant: [
    { required: true, message: '请输入领料人员', trigger: 'blur' },
  ],
  outName: [
    { required: true, message: '请输入出库人员', trigger: 'blur' },
  ],
  remark: [
    { required: true, message: '请输入备注', trigger: 'blur' },
  ],
  outCount: [
    { required: true, message: '请输入出库数量', trigger: 'blur' }, { pattern: /^[1-9]\d*$/, message: "日产量必须为正整数" }
  ],
  ProCode: [
    { required: true, message: '请输入生产单号', trigger: 'blur' } 
  ],
});
//添加生产单号
const addProduceCode = () => {
  // //判断多选框长度
  // if (multipleTableRef.value.length !== 1) {
  //   ElMessage.error('请选择且只选择一条生产单号');
  //   return;
  // }
  //ruleForm.ProCode = tableData.value[0].ProCode;
  // 关闭弹出框
  dialogTableVisible.value = false
}

//获取生产列表用于弹出框添加出库信息
const fetchData = async () => {
  try {
    const response = await axios.get(`OutWareHouse/GetProduceShows?pageIndex=${pagination.pageIndex}&pageSize=${pagination.pageSize}`)
    const data = response.data
    tableData.value = data.Data
    pagination.total = data.TotalCount
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}
//获取多选框选中的值
const handleSelectionChange = (val) => {
   //multipleTableRef.value = val.map(item => item.label);
  // console.log(multipleTableRef.value)
  if (val.length > 1) {
    ElMessage.error('请选择且只选择一条生产单号');
    return;
  }
  ruleForm.ProCode = val[0].ProCode;
}
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val
  fetchData()
}
//定义系统编号默认不勾选
const systemNumberChecked = ref(false);
//生成系统编号
const generateSystemNumber = () => {
  if (systemNumberChecked.value) {
    ruleForm.outNum = "CK" + formatDate(new Date(), "yyyymdhis");
  } else {
    //ruleForm.outNum = "CK" + formatDate(new Date(), "yyyymdhis");
    ruleForm.outNum = '';
  }
};
//添加
const submitForm = async (formEl: FormInstance | undefined) => {

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //ruleForm.outWareHouse.values = ruleForm.outWareHouse.toString();
      // ruleForm.outType = "内部领用";

      //ruleForm.outNum = "CK" + formatDate(new Date(), "yyyymdhis")
      ruleForm.outWareHouse = Warehouse.value.join(',');
      console.log(Warehouse.value.join(','))
      axios
        .post(`OutWareHouse/AddOutTab?ProCode=${ruleForm.ProCode}`, ruleForm)
        .then((res) => {
          console.log(res.data)
          if (res.data > 0) {
            ElMessage.success("添加成功");
            router.push("/UserList/outshow");
          } else {
            ElMessage.error("添加失败");
          }
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 调用后端接口获取仓库树形图数据
const getOutList = () => {
  // 在此处调用后端接口获取仓库树形图数据，将返回的数据赋值给 warehouses
  axios.get('OutWareHouse/GetWarehousesList?pid=0').then(res => {
    //console.log(res.data)
    warehousesOptions.value = res.data;
  });
};
//获取出库类型
const getOutType = () => {
  if (Array.isArray(route.query.type)) {
    // 如果是数组，则取第一个元素作为参数值
    ruleForm.outType = route.query.type[0] || '';
  } else {
    // 如果不是数组，则直接赋值
    ruleForm.outType = route.query.type || '';
  }
}
getOutType();
getOutList();
fetchData();
</script>
